﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using TomNet.IMSC.Core.Contracts.Decoration;
using TomNet.IMSC.Core.Contracts.Organization;
using TomNet.IMSC.Core.Contracts.Common;
using TomNet.IMSC.Core.Contracts.Account;
using TomNet.IMSC.Model.DbModels.Decoration;
using TomNet.IMSC.Web.Filters;
using TomNet.IMSC.Web.Models.ApiParams;
using TomNet.Web.Mvc.UI;
using TomNet.Web.WebApi;
using System.Web.Http.Controllers;
using TomNet.IMSC.Web.Common;
using TomNet.IMSC.Model.DbModels.Common;
using System.Reflection;

namespace TomNet.IMSC.Web.Controllers.API
{
    [Description("API-账户")]
    [ApiAuthentication]
    public class DecorationController : BaseApiController
    {
        public IDecorationCompanyContract DecorationCompanyContract { get; set; }// 装修公司
        public IDecorationCompanyStoreContract DecorationCompanyStoreContract { get; set; }/// 门店
        public IDecorationConsultantContract DecorationConsultantContract { get; set; }// 装修顾问
        public IDecorationRunningsContract DecorationRunningsContract { get; set; }// 流水表
        public IDecorationCompanyBrokerageGroupContract DecorationCompanyBrokerageGroupContract { get; set; }// 佣金分组
        public IImagesContract ImagesContract { get; set; }//图片
        public IIntermediaryContract IntermediaryContract { get; set; }//中介
        public IIntermediaryStaffContract IntermediaryStaffContract { get; set; }//中介业务员
        public IUsersContract UsersContract { get; set; }//经纪人User
        public ICustomerPhoneContract CustomerPhoneContract { get; set; }//客户电话
        public ICustomerContract CustomerContract { get; set; }
        public IAdvertisementContract AdvertisementContract { get; set; }//广告
        public IStaffContract StaffContract { get; set; }//管理人员
        public IBrokerageSettleAccountsRunningsContract BrokerageSettleAccountsRunningsContract { get; set; }//佣金管理
        public IBrokerageRunningsContract BrokerageRunningsContract { get; set; }
        public IDecorationCompanyCaseContract DecorationCompanyCaseContract { get; set; }//装修案例
        public IDecorationCompanyCaseItemContract DecorationCompanyCaseItemContract { get; set; }//装修项目
        public IDictionaryContract DictionaryContract { get; set; }//字典
        public IMessageBoardsContract MessageBoardsContract { get; set; }//跟进信息
        public IUsersRolesContract UsersRolesContract { set; get; }

        #region 装修报备
        [Description("API-装修报备")]
        public IHttpActionResult ttInsertDecorationRunning([FromBody]DecorationRunningModel entity)
        {
            var userid = BaseWebApiExt.GetUserIDByToken();//获取token中userid

            DecorationRunnings dr = new DecorationRunnings();
            dr.IntermediaryID = UsersContract.GetByKey(userid).IntermediaryID;//

            if (IntermediaryStaffContract.Entities.Count(p => p.ModuleID == 4 && p.IntermediaryID == dr.IntermediaryID) == 0)
            {
                var result = new AjaxResult("本店暂时无人接管，无法报备", AjaxResultType.Error);
                return Token(result, "");
            }

            dr.SellStaffID = IntermediaryStaffContract.Entities.FirstOrDefault(p => p.ModuleID == 4 && p.IntermediaryID == dr.IntermediaryID).StaffID;//销售id

            dr.AgentID = DecorationCompanyContract.GetByKey(entity.DecorationCompanyID).AgentID;
            dr.DecorationCompanyID = DecorationCompanyContract.GetByKey(entity.DecorationCompanyID).Id;//装修公司Id
            dr.DecorationCompanyName = DecorationCompanyContract.GetByKey(entity.DecorationCompanyID).Name;//装修公司
            dr.UserID = userid;//经纪人id
            dr.UserName = UsersContract.GetByKey(userid).Name;//经纪姓名
            dr.UserPhone = UsersContract.GetByKey(userid).Phone;//经纪人电话
            dr.CustomerID = entity.CustomerID;//客户ID
            dr.CustomerName = CustomerContract.GetByKey(entity.CustomerID).Name;//客户name
            dr.CustomerPhone = CustomerPhoneContract.GetByKey(entity.CustomerPhoneID).Phone;//客户电话
            dr.CustomerAddress = entity.CustomerAddress;//客户地址
            dr.Remark = entity.Remark;//备注
            dr.Area = entity.Area;//签约面积
            dr.IntermediaryName = IntermediaryContract.GetByKey(dr.IntermediaryID).Name;//中介************
            dr.FilingTime = DateTime.Now;//报备时间
            dr.State = 1;//状态默认1
            dr.StarTarget = "0";//星标
            dr.OriginStaffID = DecorationCompanyContract.GetByKey(entity.DecorationCompanyID).MediumOfCommunicationStaffID;//渠道ID

            //时间初始化
            dr.FilingTime = DateTime.Now;
            dr.FilingAuditingTime = DateTime.Now;
            dr.BandSawTime = DateTime.Now;
            dr.SubscribeTime = DateTime.Now;
            dr.DownPaymentTime = DateTime.Now;
            dr.CompleteTime = DateTime.Now;
            dr.ReturnTime = DateTime.Now;
            dr.ReturnAuditingTime = DateTime.Now;

            if (DecorationRunningsContract.Insert(dr) > 0)
            {
                var result = new AjaxResult("报备成功", AjaxResultType.Success, dr.Id);
                return Token(result, "");
            }
            else
            {
                var result = new AjaxResult("报备失败", AjaxResultType.Error);
                return Token(result, "");
            }

        }
        #endregion

        #region 装修公司列表
        [Description("API-装修公司列表")]
        public IHttpActionResult ttGetDecorationCompanyList([FromBody]DecorationCompanyModel entity)
        {
            var query = DecorationCompanyContract.Entities;

            //条件搜索
            if (!string.IsNullOrWhiteSpace(entity.KeyWord))
            {
                query = query.Where(d => d.Name.Contains(entity.KeyWord));
            }
            var list = (from m in query
                        where !m.IsDeleted
                        let img = (from m1 in ImagesContract.Entities where m1.GroupID == 6 && m1.InterfixID == m.Id && m1.IsDeleted == false orderby m1.Id select (m1.ImagePath + m1.FileName)).FirstOrDefault()
                        select new DecorationCompanyListModel
                        {
                            Id = m.Id,
                            Name = m.Name,
                            Brokerage = m.Brokerage,//佣金
                            CommissionAccount = m.CommissionAccount,//佣金帐期
                            AwardDescription = m.AwardDescription,//奖励说明
                            ImagePath = (img == null) ? "" : img.Replace(@"\", "/"),
                            AdList = AdvertisementContract.Entities.Where(a => a.ModuleID == 4).ToList(),
                            CreatedTime = m.CreatedTime
                        });
            
            //数据总数
            var total = list.Count();

            //默认给一个排序的字段
            list = list.OrderByDescending(m => m.CreatedTime);

            //分页(假如total == 0，则取消分页查询，提高性能)
            list = total > 0 ? list.Skip((entity.PageIndex - 1) * entity.PageSize).Take(entity.PageSize)
                : Enumerable.Empty<DecorationCompanyListModel>().AsQueryable();// null;

            //list = ExtMethod.HandleListValue<DecorationCompanyListModel>(list.ToList());

            var listend = list.ToList();

            ExtMethod.HandleListValue(listend);//处理null

            var result = new AjaxResultRow("成功", AjaxResultType.Success, listend, total);
            return Token(result, "");
        }
        #endregion



        #region 装修公司详情
        [Description("API-装修公司详情")]
        public IHttpActionResult ttGetDecorationCompanyInfo([FromBody]DecorationCompany entity)
        {
            var model = DecorationCompanyContract.Entities.Where(m => m.Id == entity.Id).FirstOrDefault();

            if (model != null)
            {
                ExtMethod.HandleModelValue<DecorationCompany>(model);

                var brokeragelist = DecorationCompanyBrokerageGroupContract.Entities.Where(g => g.DecorationCompanyID == entity.Id).ToList();
                var storeList = DecorationCompanyStoreContract.Entities.Where(g => g.DecorationCompanyID == entity.Id).ToList();
                var consultantList = (from q in DecorationConsultantContract.Entities
                                      join g in DecorationCompanyStoreContract.Entities
                                      on q.DecorationCompanyStoreID equals g.Id
                                      where g.DecorationCompanyID == entity.Id
                                      select q).ToList();
                var ImagePath = (from m1 in ImagesContract.Entities where m1.GroupID == 6 && m1.InterfixID == entity.Id && m1.IsDeleted == false orderby m1.Id select (m1.ImagePath + m1.FileName)).FirstOrDefault();
                if (ImagePath == null)
                    ImagePath = "";

                var staffname = (from s in StaffContract.Entities where s.Id == model.MediumOfCommunicationStaffID select s.Name).FirstOrDefault();
                var staffphone = (from s in StaffContract.Entities where s.Id == model.MediumOfCommunicationStaffID select s.Phone).FirstOrDefault();
                var CaseCount = (from c in DecorationCompanyCaseContract.Entities where c.DecorationCompanyID == entity.Id select c.Id).Count();//案例个数

                var DecorationCasePartList = (from c1 in DecorationCompanyCaseContract.Entities
                                              where c1.DecorationCompanyID == entity.Id
                                              let img = (from a in DecorationCompanyCaseItemContract.Entities
                                                         join m in ImagesContract.Entities
                                                         on a.Id equals m.InterfixID
                                                         where a.DecorationCompanyCaseID == c1.Id && m.GroupID == 12 && m.IsDeleted == false
                                                         orderby m.Id
                                                         select (m.ImagePath + m.FileName)).FirstOrDefault()
                                              let style = (from d in DictionaryContract.Entities where d.Id == c1.Style select d.Value).FirstOrDefault()

                                              select new DecorationCasePart
                                              {
                                                  id = c1.Id,
                                                  CaseImagePath = (img == null) ? "" : img.Replace(@"\", "/"),
                                                  Name = c1.Name,
                                                  Content = c1.ShowPrice + "/" + c1.Area + "/" + style + "/其他"
                                              }).Take(10).ToList();

                DecorationCasePartList.RemoveAll(d => d.CaseImagePath == "");

                var result = new AjaxResult("成功", AjaxResultType.Success, new DecorationInfoModel { BaseInfo = model, BrokerageGroupList = brokeragelist, StoreList = storeList, ConsultantList = consultantList, ImagePath = ImagePath, StaffName = staffname, StaffPhone = staffphone, CaseCount = CaseCount, DecorationCasePartList = DecorationCasePartList });
                return Token(result, "");
            }
            else
            {
                var result = new AjaxResult("失败", AjaxResultType.Error);
                return Token(result, "");
            }
        }
        #endregion

        #region 装修报备列表
        [Description("API-装修报备列表")]
        public IHttpActionResult ttGetDecorationRunningList([FromBody]DecorationRunningListModel entity)
        {
            //获取UserID
            int userid = BaseWebApiExt.GetUserIDByToken();

            var query = DecorationRunningsContract.Entities;

            //判断用户角色是否为店长
            if (UsersRolesContract.Entities.Count(m => m.UserID == userid && m.IntermediaryRoleID > 0) > 0)
            {
                var userModel = UsersContract.GetByKey(userid);
                query = query.Where(m => m.IntermediaryID == userModel.IntermediaryID);//查看当前门店的报备
            }
            else
            {
                query = query.Where(m => m.UserID == userid);//查看经纪人自己报备的
            }

            //数据总数
            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.FilingTime);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((entity.PageIndex - 1) * entity.PageSize).Take(entity.PageSize)
                : Enumerable.Empty<DecorationRunnings>().AsQueryable();// null;

            List<DecorationRunningListShowModel> list = new List<DecorationRunningListShowModel>();

            foreach (var item in query)
            {
                var temp = new DecorationRunningListShowModel();
                temp.Id = item.Id;
                temp.DecorationCompanyName = item.DecorationCompanyName;
                temp.CustomerName = item.CustomerName;
                temp.CustomerPhone = item.CustomerPhone;
                temp.CustomerAddress = item.CustomerAddress;
                temp.Area = item.Area;
                temp.UserName = item.UserName;
                temp.Remark = item.Remark;

                //1 报备待审 2 报备通过 3 报备驳回 4 已到店或量尺 5 已交定金 6 已付首款 7 验收 8 退单 
                switch (item.State)
                {
                    case 1:
                        temp.State = "报备待审";
                        temp.OperTime = item.FilingTime.ToString("yy-MM-dd HH:mm");
                        break;
                    case 2:
                        temp.State = "报备通过";
                        temp.OperTime = item.FilingAuditingTime.ToString("yy-MM-dd HH:mm");
                        break;
                    case 3:
                        temp.State = "报备驳回";
                        temp.OperTime = item.FilingAuditingTime.ToString("yy-MM-dd HH:mm");
                        break;
                    case 4:
                        temp.State = "已到店或量尺";
                        temp.OperTime = item.BandSawTime.ToString("yy-MM-dd HH:mm");
                        break;
                    case 5:
                        temp.State = "已交定金";
                        temp.OperTime = item.SubscribeTime.ToString("yy-MM-dd HH:mm");
                        break;
                    case 6:
                        temp.State = "已付首期工程款";
                        temp.OperTime = item.DownPaymentTime.ToString("yy-MM-dd HH:mm");
                        break;
                    case 7:
                        temp.State = "已验收";
                        temp.OperTime = item.CompleteTime.ToString("yy-MM-dd HH:mm");
                        break;
                    default:
                        temp.State = "";
                        temp.OperTime = "";
                        break;
                }

                //退房
                if (item.ReturnState == 1)
                {
                    temp.State = "退单待审";
                    temp.OperTime = item.ReturnTime.ToString("yy-MM-dd HH:mm");
                }
                if (item.ReturnState == 2)
                {
                    temp.State = "已退单";
                    temp.OperTime = item.ReturnAuditingTime.ToString("yy-MM-dd HH:mm");
                }

                list.Add(temp);
            }


            //var result = new AjaxResult("成功", AjaxResultType.Success, list);
            var result = new AjaxResultRow("成功", AjaxResultType.Success, list, total);
            return Token(result, "");
        }
        #endregion

        #region 查看装修报备订单
        [Description("API-查看装修报备订单")]
        public IHttpActionResult ttGetRunningModel([FromBody]DecorationRunnings entity)
        {

            var model = DecorationRunningsContract.GetByKey(entity.Id);
            //State：1报备待审   2报备通过   3报备驳回   4已量尺   5已交定金   6已交首期工程款   7已验收完成   8已退
            //退单状态 ReturnState: 0 默认 1 退单待审 2 已退单
            //模板选择： 1 报备+通过 2 报备+未通过 3 带看 4 完成
            //图标形状： 1 进行中，橘黄色 2 已完成，绿色 3 等待，灰色 4 拒绝，红色
            //颜色值： 橘黄色=#F57035 绿色=#3AB394 灰色 =#B3B3B3 红色=#F40001

            if (model != null)
            {
                var query = new DecorationRunningInfoModel();
                query.Id = model.Id;
                query.UserName = model.UserName;
                query.UserPhone = model.UserPhone;
                query.State = model.State;
                query.Area = model.Area;//面积
                query.CustomerAddress = model.CustomerAddress;//地址
                query.Remark = model.Remark;//备注

                query.DecorationRunningsInfoShowList = new List<DecorationRunningInfoShowModel>();//流水步骤集合

                #region 报备
                //1 报备
                var FilingModel = new DecorationRunningInfoShowModel();
                FilingModel.SortID = 1;
                FilingModel.ModuleName = "报备";

                switch (model.State)
                {
                    case 1://报备待审
                        FilingModel.StyleID = 1;//模板1                        
                        FilingModel.ModuleNameColor = "#F57035";//橘黄色
                        FilingModel.ModuleIcon = 1;//进行中
                        FilingModel.ModuleIconColor = "#F57035";//橘黄色
                        FilingModel.Title = "报备客户";
                        FilingModel.OperTime = model.FilingTime.ToString("yy-MM-dd HH:mm");
                        FilingModel.ViceTitle = "等待审核";
                        FilingModel.ViceTitleColor = "#F57035";//橘黄色
                        break;
                    case 3://报备驳回
                        FilingModel.StyleID = 2;//模板2
                        FilingModel.ModuleNameColor = "#F40001";//红色
                        FilingModel.ModuleIcon = 4;//拒绝
                        FilingModel.ModuleIconColor = "#F40001";//红色
                        FilingModel.Title = "报备客户";
                        FilingModel.OperTime = model.FilingAuditingTime.ToString("yy-MM-dd HH:mm");
                        FilingModel.ViceTitle = "审核未通过";
                        FilingModel.ViceTitleColor = "#F40001";//红色
                        FilingModel.FilingAuditingRemark = model.FilingAuditingRemark;//报备审核说明
                        break;
                    case 2:
                    case 4:
                    case 5:
                    case 6:
                    case 7:
                        FilingModel.StyleID = 1;//模板1
                        FilingModel.ModuleNameColor = "#3AB394";//绿色
                        FilingModel.ModuleIcon = 2;//已完成
                        FilingModel.ModuleIconColor = "#3AB394";//绿色
                        FilingModel.Title = "报备客户";
                        FilingModel.OperTime = model.FilingAuditingTime.ToString("yy-MM-dd HH:mm");
                        FilingModel.ViceTitle = "审核通过";
                        FilingModel.ViceTitleColor = "#3AB394";//绿色
                        break;
                }

                query.DecorationRunningsInfoShowList.Add(FilingModel);
                #endregion

                #region 带看（量尺）          
                var BandSawModel = new DecorationRunningInfoShowModel();
                BandSawModel.SortID = 2;
                BandSawModel.ModuleName = "到店或量尺";

                switch (model.State)
                {
                    case 1://报备待审
                    case 3://报备驳回
                        BandSawModel.StyleID = 4;//模板4                        
                        BandSawModel.ModuleNameColor = "#B3B3B3";//灰色
                        BandSawModel.ModuleIcon = 3;//等待
                        BandSawModel.ModuleIconColor = "#B3B3B3";//灰色
                        break;
                    case 2://报备通过 （到店量尺进行中）
                        BandSawModel.StyleID = 3;//模板3
                        BandSawModel.ModuleNameColor = "#F57035";//橘黄色
                        BandSawModel.ModuleIcon = 1;//进行中
                        BandSawModel.ModuleIconColor = "#F57035";//橘黄色
                        BandSawModel.Title = "可到店或量尺";
                        BandSawModel.OperTime = "";//带看时间
                        BandSawModel.ViceTitle = "";
                        BandSawModel.ViceTitleColor = "";
                        BandSawModel.IsCameraButton = 1;//有照相按钮
                        BandSawModel.GroupID = 7;//分组                               
                        BandSawModel.ImageType = 1;//带看单
                        BandSawModel.ImageRemark = "到店或量尺后请上传照片，\"客户带看单\"照片为必传照片，带看单必需有置业顾问、经纪人、项目经理签字，其他照片可以是\"客户与售楼员合影\"、\"客户与经纪人合影\"等等!";
                        BandSawModel.ImageList = ImagesContract.Entities.Where(m1 => m1.GroupID == 7 && m1.ImageType == 1 && m1.InterfixID == entity.Id && m1.IsDeleted == false).ToList();//带看图片集合
                        BandSawModel.IsViewButton = 1;//有查看按钮
                        BandSawModel.ViewButtonText = "查看\"客户带看单\"范例";//查看按钮文本
                        BandSawModel.ViewButtonValue = "";//查看按钮链接地址
                        break;
                    case 4://已量尺
                    case 5://已交定金
                    case 6://已交首期工程款
                    case 7://验收成功
                        BandSawModel.StyleID = 3;//模板3
                        BandSawModel.ModuleNameColor = "#3AB394";//绿色
                        BandSawModel.ModuleIcon = 2;//已完成
                        BandSawModel.ModuleIconColor = "#3AB394";//绿色
                        BandSawModel.Title = "已到店或量尺";
                        BandSawModel.OperTime = model.BandSawTime.ToString("yy-MM-dd HH:mm");
                        BandSawModel.ViceTitle = "";
                        BandSawModel.ViceTitleColor = "";
                        BandSawModel.IsCameraButton = 1;//有照相按钮
                        BandSawModel.GroupID = 7;//分组
                        BandSawModel.ImageType = 1;//带看单
                        BandSawModel.ImageRemark = "到店或量尺后请上传照片，\"客户带看单\"照片为必传照片，带看单必需有置业顾问、经纪人、项目经理签字，其他照片可以是\"客户与售楼员合影\"、\"客户与经纪人合影\"等等!";
                        BandSawModel.ImageList = ImagesContract.Entities.Where(m1 => m1.GroupID == 7 && m1.ImageType == 1 && m1.InterfixID == entity.Id && m1.IsDeleted == false).ToList();//带看图片集合
                        BandSawModel.IsViewButton = 1;//有查看按钮
                        BandSawModel.ViewButtonText = "查看\"客户带看单\"范例";//查看按钮文本
                        BandSawModel.ViewButtonValue = "";//查看按钮链接地址
                        break;
                }
                query.DecorationRunningsInfoShowList.Add(BandSawModel);
                #endregion

                #region 定金
                //3 定金
                var SubscribewModel = new DecorationRunningInfoShowModel();
                SubscribewModel.SortID = 3;
                SubscribewModel.ModuleName = "定金";

                switch (model.State)
                {
                    case 1://报备待审                   
                    case 2://报备通过
                    case 3://报备驳回
                        SubscribewModel.StyleID = 4;//模板4                        
                        SubscribewModel.ModuleNameColor = "#B3B3B3";//灰色
                        SubscribewModel.ModuleIcon = 3;//等待
                        SubscribewModel.ModuleIconColor = "#B3B3B3";//灰色                        
                        break;
                    case 4://量尺完成（进行交定金黄色）
                        SubscribewModel.StyleID = 3;//模板3
                        SubscribewModel.ModuleNameColor = "#F57035";//橘黄色
                        SubscribewModel.ModuleIcon = 1;//进行中
                        SubscribewModel.ModuleIconColor = "#F57035";//橘黄色
                        SubscribewModel.Title = "可交定金";
                        SubscribewModel.OperTime = "";//签约时间
                        SubscribewModel.ViceTitle = "";
                        SubscribewModel.ViceTitleColor = "";
                        SubscribewModel.IsCameraButton = 1;//有照相按钮
                        SubscribewModel.GroupID = 7;//分组
                        SubscribewModel.ImageType = 2;//定金成交单
                        SubscribewModel.ImageRemark = "请上传\"定金确认单\"照片！";
                        SubscribewModel.ImageList = ImagesContract.Entities.Where(m1 => m1.GroupID == 7 && m1.ImageType == 2 && m1.InterfixID == entity.Id && m1.IsDeleted == false).ToList();//成交协议图片集合
                        SubscribewModel.IsViewButton = 1;//有查看按钮
                        SubscribewModel.ViewButtonText = "查看\"客户带看单\"范例";//查看按钮文本
                        SubscribewModel.ViewButtonValue = "";//查看按钮链接地址
                        break;
                    case 5://已交定金                     
                    case 6://已交首期
                    case 7://验收
                        SubscribewModel.StyleID = 3;//模板3
                        SubscribewModel.ModuleNameColor = "#3AB394";//绿色
                        SubscribewModel.ModuleIcon = 2;//已完成
                        SubscribewModel.ModuleIconColor = "#3AB394";//绿色
                        SubscribewModel.Title = "已交定金";
                        SubscribewModel.OperTime = model.SubscribeTime.ToString("yy-MM-dd HH:mm");
                        SubscribewModel.ViceTitle = "";
                        SubscribewModel.ViceTitleColor = "";
                        SubscribewModel.IsCameraButton = 1;//有照相按钮
                        SubscribewModel.GroupID = 7;//分组
                        SubscribewModel.ImageType = 2;//定金成交单
                        SubscribewModel.ImageRemark = "请上传\"定金确认单\"照片！";
                        SubscribewModel.ImageList = ImagesContract.Entities.Where(m1 => m1.GroupID == 7 && m1.ImageType == 2 && m1.InterfixID == entity.Id && m1.IsDeleted == false).ToList();//成交协议图片集合
                        SubscribewModel.IsViewButton = 1;//有查看按钮
                        SubscribewModel.ViewButtonText = "查看\"客户带看单\"范例";//查看按钮文本
                        SubscribewModel.ViewButtonValue = "";//查看按钮链接地址
                        break;
                }
                query.DecorationRunningsInfoShowList.Add(SubscribewModel);
                #endregion

                #region 4首付
                var DownPaymentModel = new DecorationRunningInfoShowModel();
                DownPaymentModel.SortID = 4;
                DownPaymentModel.ModuleName = "首期工程款";

                switch (model.State)
                {
                    case 1://报备待审                   
                    case 2://报备通过
                    case 3://报备驳回
                    case 4://量尺完成
                        DownPaymentModel.StyleID = 4;//模板4                        
                        DownPaymentModel.ModuleNameColor = "#B3B3B3";//灰色
                        DownPaymentModel.ModuleIcon = 3;//等待
                        DownPaymentModel.ModuleIconColor = "#B3B3B3";//灰色                        
                        break;
                    case 5://交完定金                        
                        DownPaymentModel.StyleID = 3;//模板3
                        DownPaymentModel.ModuleNameColor = "#F57035";//橘黄色
                        DownPaymentModel.ModuleIcon = 1;//进行中
                        DownPaymentModel.ModuleIconColor = "#F57035";//橘黄色
                        DownPaymentModel.Title = "可交首期工程款";
                        DownPaymentModel.OperTime = "";//签约时间
                        DownPaymentModel.ViceTitle = "";
                        DownPaymentModel.ViceTitleColor = "";
                        DownPaymentModel.IsCameraButton = 1;//有照相按钮
                        DownPaymentModel.GroupID = 7;//分组
                        DownPaymentModel.ImageType = 3;//首期工程款成交单
                        DownPaymentModel.ImageRemark = "请上传\"首期工程款确认单\"照片！";
                        DownPaymentModel.ImageList = ImagesContract.Entities.Where(m1 => m1.GroupID == 7 && m1.ImageType == 3 && m1.InterfixID == entity.Id && m1.IsDeleted == false).ToList();//成交协议图片集合
                        DownPaymentModel.IsViewButton = 1;//有查看按钮
                        DownPaymentModel.ViewButtonText = "查看\"客户带看单\"范例";//查看按钮文本
                        DownPaymentModel.ViewButtonValue = "";//查看按钮链接地址
                        break;
                    case 6://已交首期
                    case 7://验收                    
                        DownPaymentModel.StyleID = 3;//模板3
                        DownPaymentModel.ModuleNameColor = "#3AB394";//绿色
                        DownPaymentModel.ModuleIcon = 2;//已完成
                        DownPaymentModel.ModuleIconColor = "#3AB394";//绿色
                        DownPaymentModel.Title = "已交首期工程款";
                        DownPaymentModel.OperTime = model.DownPaymentTime.ToString("yy-MM-dd HH:mm");
                        DownPaymentModel.ViceTitle = "";
                        DownPaymentModel.ViceTitleColor = "";
                        DownPaymentModel.IsCameraButton = 1;//有照相按钮
                        DownPaymentModel.GroupID = 7;//分组
                        DownPaymentModel.ImageType = 3;//首期工程款成交单
                        DownPaymentModel.ImageRemark = "请上传\"首期工程款确认单\"照片！";
                        DownPaymentModel.ImageList = ImagesContract.Entities.Where(m1 => m1.GroupID == 7 && m1.ImageType == 3 && m1.InterfixID == entity.Id && m1.IsDeleted == false).ToList();//成交协议图片集合
                        DownPaymentModel.IsViewButton = 1;//有查看按钮
                        DownPaymentModel.ViewButtonText = "查看\"客户带看单\"范例";//查看按钮文本
                        DownPaymentModel.ViewButtonValue = "";//查看按钮链接地址
                        break;
                }
                query.DecorationRunningsInfoShowList.Add(DownPaymentModel);
                #endregion

                #region 5验收
                var CompleteModel = new DecorationRunningInfoShowModel();
                CompleteModel.SortID = 5;

                switch (model.State)
                {
                    case 1://报备待审                   
                    case 2://报备通过
                    case 3://报备驳回
                    case 4://量尺完成
                    case 5://交完定金
                        CompleteModel.StyleID = 4;//模板4    
                        CompleteModel.ModuleName = "验收";
                        CompleteModel.ModuleNameColor = "#B3B3B3";//灰色
                        CompleteModel.ModuleIcon = 3;//等待
                        CompleteModel.ModuleIconColor = "#B3B3B3";//灰色                        
                        break;
                    case 6://已交首期
                        CompleteModel.StyleID = 4;//模板4
                        CompleteModel.ModuleName = "验收";
                        CompleteModel.ModuleNameColor = "#F57035";//橘黄色
                        CompleteModel.ModuleIcon = 1;//已完成
                        CompleteModel.ModuleIconColor = "#F57035";//橘黄色
                        break;
                    case 7://验收                    
                        if (model.ReturnState.Equals(2))//已退单
                        {
                            CompleteModel.StyleID = 1;//模板1
                            CompleteModel.ModuleName = "验收";
                            CompleteModel.ModuleNameColor = "#F40001";//红色
                            CompleteModel.ModuleIcon = 4;//拒绝
                            CompleteModel.ModuleIconColor = "#F40001";//红色
                            CompleteModel.Title = "已退单";
                            CompleteModel.OperTime = model.ReturnAuditingTime.ToString("yy-MM-dd HH:mm");//退单审核时间
                            CompleteModel.ViceTitle = "";//副标题  没有内容
                            CompleteModel.ViceTitleColor = "";//副标题  没有颜色 
                        }
                        else//正常
                        {
                            CompleteModel.StyleID = 4;//模板4
                            CompleteModel.ModuleName = "验收（" + model.CompleteTime.ToString("yy-MM-dd HH:mm") + "）";
                            CompleteModel.ModuleNameColor = "#3AB394";//绿色
                            CompleteModel.ModuleIcon = 2;//已完成
                            CompleteModel.ModuleIconColor = "#3AB394";//绿色
                            break;
                        }
                        break;
                }
                query.DecorationRunningsInfoShowList.Add(CompleteModel);
                #endregion



                //跟进信息====================================================================================================

                query.MessageBoardsShowList = (from m in MessageBoardsContract.Entities
                                               join n in StaffContract.Entities
                                               on m.StaffID equals n.Id into tempb
                                               from b in tempb.DefaultIfEmpty()
                                               where m.MessageBoardsType == 6 && m.InterfixID == model.Id && m.IsDeleted == false
                                               select new
                                               {
                                                   StaffName = b.Name == null ? "" : b.Name,
                                                   Content = m.Content,
                                                   CreatedTime = m.CreatedTime
                                               }).ToList()
                                               .Select(m => new MessageBoardsShowModel
                                               {
                                                   StaffName = m.StaffName,
                                                   Content = m.Content,
                                                   CreatedTime = m.CreatedTime.ToString("yy-MM-dd HH:mm")
                                               }).ToList();//跟进信息集合


                //====================================================================================================


                //佣金计算
                decimal totalAmount = 0;//应得佣金
                decimal taxAmount = 0;//税款
                decimal achieveAmount = 0;//已结佣金                
                decimal unAchieveAmount = 0;//未结佣金
                int brokerageState = 1;//佣金流水状态

                //应得佣金 参照表BrokerageType
                var brokerageRunningsModel = BrokerageRunningsContract.Entities.Where(m => m.ModuleID == 4 && m.RunningsID == model.Id && m.BrokerageTypeID == 10).FirstOrDefault();
                if (brokerageRunningsModel != null)
                {
                    totalAmount = brokerageRunningsModel.Amount;
                    taxAmount = brokerageRunningsModel.Tax;
                    brokerageState = brokerageRunningsModel.State;
                    achieveAmount = BrokerageSettleAccountsRunningsContract.Entities.Count(m => m.BrokerageRunningsID == brokerageRunningsModel.Id) > 0 ? BrokerageSettleAccountsRunningsContract.Entities.Where(m => m.BrokerageRunningsID == brokerageRunningsModel.Id).Sum(p => p.Amount) : 0;
                }
                unAchieveAmount = totalAmount - taxAmount - achieveAmount;

                query.TotalAmount = totalAmount.ToString("0.00") + "元";
                query.TaxAmount = taxAmount.ToString("0.00") + "元";
                query.AchieveAmount = achieveAmount.ToString("0.00") + "元";
                query.UnAchieveAmount = unAchieveAmount.ToString("0.00") + "元";
                switch (brokerageState)
                {
                    case 0:
                    case 1:
                        query.BrokerageState = 2;
                        break;
                    case 2:
                    case 3:
                    case 4:
                    case 5:
                        query.BrokerageState = 1;
                        break;
                }

                var result = new AjaxResult("成功", AjaxResultType.Success, query);
                return Token(result, "");
            }
            else
            {
                var result = new AjaxResult("失败", AjaxResultType.Error);
                return Token(result, "");
            }

        }
        #endregion

        #region 装修案例列表
        [Description("API-装修报备列表")]
        public IHttpActionResult ttGetDecorationCaseList([FromBody]DecorationCaseListModel entity)
        {
            //获取UserID
            int userid = BaseWebApiExt.GetUserIDByToken();

            var query1 = DecorationCompanyCaseContract.Entities.Where(m => m.DecorationCompanyID == entity.DecorationCompanyId);
            //类型选择
            if (entity.HouseType != 0)
            {
                query1 = query1.Where(d => d.HouseType == entity.HouseType);
            }
            if (entity.Style != 0)
            {
                query1 = query1.Where(d => d.Style == entity.Style);
            }
            if (entity.AreaTag != 0)
            {
                query1 = query1.Where(d => d.AreaTag == entity.AreaTag);
            }

            var query = from d in query1
                        where d.DecorationCompanyID == entity.DecorationCompanyId
                        let img = (from a in DecorationCompanyCaseItemContract.Entities
                                   join m in ImagesContract.Entities
                                   on a.Id equals m.InterfixID
                                   where a.DecorationCompanyCaseID == d.Id && m.GroupID == 12 && m.IsDeleted == false
                                   orderby m.Id
                                   select (m.ImagePath + m.FileName)).FirstOrDefault()
                        let style = (from s in DictionaryContract.Entities where s.Id == d.Style select s.Value).FirstOrDefault()
                        select new DecorationCasePart
                        {
                            id = d.Id,
                            CaseImagePath = (img == null) ? "" : img.Replace(@"\", "/"),
                            Name = d.Name,
                            Content = d.ShowPrice + "/" + d.Area + "/" + style + "/其他"
                        };

            //数据总数
            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.id);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((entity.PageIndex - 1) * entity.PageSize).Take(entity.PageSize)
                : Enumerable.Empty<DecorationCasePart>().AsQueryable();// null;            

            var result = new AjaxResultRow("成功", AjaxResultType.Success, query, total); ;
            return Token(result, "");
        }
        #endregion

        #region 装修案例条件
        [Description("API-装修公司详情")]
        public IHttpActionResult ttGetCaseCondition()
        {
            Dictionary dt = new Dictionary
            {
                Id = 0,
                Value = "不限"
            };
            var HouseType = new List<Dictionary>();
            var Style = new List<Dictionary>();
            var AreaTag = new List<Dictionary>();

            HouseType.Add(dt);
            Style.Add(dt);
            AreaTag.Add(dt);
            HouseType.AddRange(DictionaryContract.Entities.Where(d => d.Name == "DecorationCaseHouseType").ToList());
            Style.AddRange(DictionaryContract.Entities.Where(d => d.Name == "DecorationCaseStyle").ToList());
            AreaTag.AddRange(DictionaryContract.Entities.Where(d => d.Name == "DecorationCaseArea").ToList());

            DecorationCaseConditionModel dcc = new DecorationCaseConditionModel()
            {
                HouseType = HouseType,
                Style = Style,
                AreaTag = AreaTag
            };

            var result = new AjaxResult("成功", AjaxResultType.Success, dcc);
            return Token(result, "");

        }
        #endregion

        #region 装修案例详情
        [Description("API-装修案例详情")]
        public IHttpActionResult ttGetDecorationCaseInfo([FromBody]DecorationCompanyCase entity)
        {
            var model = DecorationCompanyCaseContract.Entities.Where(m => m.Id == entity.Id).FirstOrDefault();
            if (model != null)
            {
                ExtMethod.HandleModelValue<DecorationCompanyCase>(model);
                var HouseType = (from d in DictionaryContract.Entities
                                 where d.Id == model.HouseType
                                 select d.Value).FirstOrDefault();
                var Area = model.Area + "㎡";
                var Style = (from d in DictionaryContract.Entities
                             where d.Id == model.Style
                             select d.Value).FirstOrDefault();

                var CaseContentList = (from c1 in DecorationCompanyCaseItemContract.Entities
                                       where c1.DecorationCompanyCaseID == entity.Id
                                       //let img = (from m in ImagesContract.Entities
                                       //           where m.InterfixID == c1.Id && m.GroupID == 12 && m.IsDeleted == false
                                       //           orderby m.Id
                                       //           select (m.ImagePath + m.FileName)).FirstOrDefault()
                                       select new CaseContentModel
                                       {
                                           title = c1.Title,
                                           img = (from m in ImagesContract.Entities
                                                  where m.InterfixID == c1.Id && m.GroupID == 12 && m.IsDeleted == false
                                                  orderby m.Id
                                                  select (m.ImagePath + m.FileName)).ToList(),
                                           comtent = c1.Content
                                       }).ToList();

                var result = new AjaxResult("成功", AjaxResultType.Success, new DecorationCaseShowModel { Model = model, Style = Style, Item = CaseContentList, Area = Area, HouseType = HouseType });
                return Token(result, "");
            }
            else
            {
                var result = new AjaxResult("失败", AjaxResultType.Error);
                return Token(result, "");
            }
        }
        #endregion
    }
}